#include "rclcpp/rclcpp.hpp"
#include "agv_srvs/srv/control_voice.hpp"
#include "io_macro.h"

#include <bitset>
#include <thread>
#include <mutex>
#include <atomic>
#include <chrono>

using namespace std::chrono_literals;

////////////////////////////// class CanSpeaker ////////////////////////////////////////
class CanSpeaker {
public:
    using AUDIO_TYPE = std::pair<int, int>;

    explicit CanSpeaker(const std::shared_ptr<rclcpp::Node>& node);
    ~CanSpeaker();

    bool enable() const { return bEnable_; }
    void setAudioMode(SoundMode mode);

    void readParameters();
    void init();
    void workerThread();

private:
    void audioOut();
    bool setAudio(AUDIO_TYPE audio);
    
    // Configuration parameters
    std::shared_ptr<rclcpp::Node> node_;
    bool bEnable_;
    AUDIO_TYPE silentAudio_;
    AUDIO_TYPE runAudio_;
    AUDIO_TYPE alarmAudio_;
    AUDIO_TYPE obstacleAudio_;
    AUDIO_TYPE spinAudio_;

    // ROS2 interfaces
    rclcpp::Client<agv_srvs::srv::ControlVoice>::SharedPtr client_;
    std::thread workerThread_;
    std::atomic<bool> running_{false};
    // timer to check server 
    rclcpp::TimerBase::SharedPtr service_check_timer_;

    // State management
    std::mutex stateMutex_;
    SoundMode currentMode_{SOUND_SILENT};
    SoundMode previousMode_{SOUND_SILENT};
};